package com.mallcloud.mall.admin.controller;

import cn.hutool.core.lang.tree.Tree;
import com.mallcloud.mall.admin.api.entity.SysMenu;
import com.mallcloud.mall.admin.service.SysMenuService;
import com.mallcloud.mall.common.core.util.R;
import com.mallcloud.mall.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Api(tags = "菜单管理模块")
@RestController
@AllArgsConstructor
@RequestMapping("/menu")
public class SysMenuController {
	private final SysMenuService sysMenuService;

	@ApiOperation("返回当前用户的树形菜单集合")
	@GetMapping
	public R<List<Tree<Long>>> getUserMenu(String type, Long parentId) {
		// 获取符合条件的菜单
		Set<SysMenu> all = new HashSet<>();
		SecurityUtils.getRoles().forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId)));
		return R.ok(sysMenuService.filterMenu(all, type, parentId));
	}

	@ApiOperation("返回树形菜单集合")
	@GetMapping(value = "/tree")
	public R<List<Tree<Long>>> getTree(Long parentId, String menuName) {
		return R.ok(sysMenuService.treeMenu(parentId, menuName));
	}

	@ApiOperation("返回角色的菜单集合")
	@GetMapping("/tree/{roleId}")
	public R<List<Long>> getRoleTree(@PathVariable Long roleId) {
		return R.ok(sysMenuService.findMenuByRoleId(roleId).stream().map(SysMenu::getMenuId).collect(Collectors.toList()));
	}

	@ApiOperation("通过ID查询菜单的详细信息")
	@GetMapping("/{id}")
	public R<SysMenu> getById(@PathVariable Long id) {
		return R.ok(sysMenuService.getById(id));
	}

	@ApiOperation("新增菜单")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_menu_add')")
	public R<Boolean> save(@Valid @RequestBody SysMenu sysMenu) {
		return R.ok(sysMenuService.saveMenu(sysMenu));
	}

	@ApiOperation("删除菜单")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_menu_del')")
	public R<Boolean> removeById(@PathVariable Long id) {
		return sysMenuService.removeMenuById(id);
	}

	@ApiOperation("更新菜单")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_menu_edit')")
	public R<Boolean> update(@Valid @RequestBody SysMenu sysMenu) {
		return R.ok(sysMenuService.updateMenuById(sysMenu));
	}

}
